<template>
    <div class="table-form-page">
        <div class="form-page-header">
            <div>
                <el-page-header @back="closeWindow" content="新增经营用品申请" />
            </div>
            <div>
                <el-button v-show="showReviewBtn" type="primary" @click="onReview">审批</el-button>
                <el-button v-show="showSaveBtn" type="warning" @click="addSupplies">添加用品</el-button>
                <el-button v-show="showSaveBtn" type="primary" @click="onSubmit">保存</el-button>
                <el-button type="default" @click="onPrint">打印</el-button>
            </div>
        </div>
        <div class="form-content">
            <table class="table-class" border="0" cellspacing="0" cellpadding="0">
                <col class="label-col" />
                <col class="content-col" />
                <col class="label-col" />
                <col class="content-col" />
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">经营信息</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">部门</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.departmentName"
                            class="form-input-class"
                            :readonly="true"
                            @click="chooseDepart"
                        />
                    </td>
                    <td class="td-class label-class">填写人</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.applyMan" class="form-input-class" :readonly="true" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">活动时间</td>
                    <td class="td-class content-class">
                        <el-date-picker
                            v-model="form.activityDate"
                            type="date"
                            value-format="YYYY-MM-DD"
                            class="form-input-class"
                            placeholder="选择日期"
                        />
                    </td>
                    <td class="td-class label-class">活动地点</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.activityAddr" class="form-input-class" placeholder="请输入地点" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">项目编码</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.projectCode"
                            class="form-input-class"
                            placeholder="请选择"
                            readonly
                            @click="chooseProject"
                        />
                    </td>
                    <td class="td-class label-class">工程项目</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.projectName"
                            class="form-input-class"
                            placeholder="请选择"
                            readonly
                            @click="chooseProject"
                        />
                    </td>
                </tr>
                <!-- <tr class="tr-class">
                    <td class="td-class label-class">工程项目</td>
                    <td class="td-class content-class" colspan="3">
                        <el-input v-model="form.projectName" class="form-input-class" placeholder="请选择" readonly @click="chooseProject" />
                    </td>
                </tr> -->
                <tr class="tr-class">
                    <td class="td-class label-class">参加人员</td>
                    <td class="td-class content-class" colspan="3">
                        <el-input v-model="form.joinMans" class="form-input-class" placeholder="请输入参加人员" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">拜访单位</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.enterprise" class="form-input-class" placeholder="请输入拜访单位" />
                    </td>
                    <td class="td-class label-class">拜访人员及职位</td>
                    <td class="td-class content-class">
                        <el-input
                            v-model="form.customAndPost"
                            class="form-input-class"
                            placeholder="请输入拜访人员及职位"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">预计费用（元）</td>
                    <td class="td-class content-class">
                        <el-input v-model="form.planFees" class="form-input-class" placeholder="自动计算" readonly />
                    </td>
                    <td class="td-class label-class">是否含酒水</td>
                    <td class="td-class content-class">
                        <el-select v-model="form.isWine" class="form-input-class" placeholder="请选择">
                            <el-option
                                v-for="item in wineOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">事由及预期效果</td>
                    <td class="td-class content-class" colspan="3">
                        <el-input
                            v-model="form.reasonAndDesired"
                            class="form-input-class"
                            placeholder="请输入事由及预期效果"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">经营用品信息</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class" colspan="4">
                        <el-table :data="form.items" border height="200">
                            <el-table-column label="品名" width="200" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-if="showSaveBtn" v-model="scope.row.name" placeholder="请输入" />
                                    <span v-else>{{ scope.row.name }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="品牌型号" width="200" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-if="showSaveBtn" v-model="scope.row.model" placeholder="请输入" />
                                    <span v-else>{{ scope.row.model }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" width="100" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-if="showSaveBtn" v-model="scope.row.unit" placeholder="请输入" />
                                    <span v-else>{{ scope.row.unit }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="数量" width="100" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-if="showSaveBtn" v-model="scope.row.num" placeholder="请输入" />
                                    <span v-else>{{ scope.row.num }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="单价（元）" width="100" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-if="showSaveBtn" v-model="scope.row.price" placeholder="请输入" />
                                    <span v-else>{{ scope.row.price }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="小计（元）" width="120" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input
                                        v-if="showSaveBtn"
                                        v-model="scope.row.subtotal"
                                        readonly
                                        placeholder="自动计算"
                                    />
                                    <span v-else>{{ scope.row.subtotal }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" min-width="200" show-overflow-tooltip>
                                <template #default="scope">
                                    <el-input v-if="showSaveBtn" v-model="scope.row.remark" placeholder="请输入" />
                                    <span v-else>{{ scope.row.remark }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column v-if="showSaveBtn" fixed="right" label="操作" width="120">
                                <template #default="scope">
                                    <el-button @click.prevent="deleteRow(scope.$index, form.items)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">客户关系维护记录</td>
                    <td class="td-class" colspan="3" style="height: 40px">
                        <el-select v-model="form.isCrmr" class="form-input-class" placeholder="请选择">
                            <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">收货地址</td>
                    <td class="td-class" colspan="3" style="height: 40px">
                        <el-input v-model="form.shippingAddr" class="form-input-class" placeholder="请输入收获地址" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">收件人</td>
                    <td class="td-class" colspan="3" style="height: 40px">
                        <el-input v-model="form.consignee" class="form-input-class" placeholder="请输入收件人" />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class label-class">手机号码</td>
                    <td class="td-class" colspan="3" style="height: 40px">
                        <el-input
                            v-model="form.consigneePhone"
                            class="form-input-class"
                            placeholder="请输入收件人手机号码"
                        />
                    </td>
                </tr>
                <tr class="tr-class">
                    <td class="tab-class" colspan="4">审批流程</td>
                </tr>
                <tr class="tr-class">
                    <td class="td-class" colspan="4">
                        <FlowCpt
                            ref="processRef"
                            :flowType="form.flowTypeCode"
                            :disabled="!showSaveBtn"
                            :taskId="id"
                        ></FlowCpt>
                        <FlowOperationCpt
                            v-if="showReviewDialog"
                            :data="form"
                            @close="closeReviewDialog"
                        ></FlowOperationCpt>
                    </td>
                </tr>
                <tr class="tr-class" v-if="showFlowHis">
                    <td class="tab-class" colspan="4">审批记录</td>
                </tr>
                <tr class="tr-class" v-if="showFlowHis">
                    <td class="td-class" colspan="4">
                        <FlowHistoryCpt :taskId="id" />
                    </td>
                </tr>
            </table>
        </div>
        <el-dialog
            title="选择部门"
            v-model="showDepartment"
            width="400px"
            :lock-scroll="true"
            :close-on-click-modal="false"
            destroy-on-close
        >
            <div class="tree-dialog-content">
                <department-tree @select="treeSelected"></department-tree>
            </div>
        </el-dialog>
        <el-dialog
            width="800px"
            top="10vh"
            title="项目"
            v-model="showProjectGridCpt"
            :lock-scroll="true"
            :close-on-click-modal="false"
        >
            <div class="dialog-content">
                <ProjectGridCpt @select="projectSelected"></ProjectGridCpt>
            </div>
        </el-dialog>
        <el-dialog
            width="840px"
            top="10vh"
            title="打印预览"
            v-model="showPrint"
            :lock-scroll="true"
            :close-on-click-modal="false"
            :destroy-on-close="true"
        >
            <PrintTemplate v-if="showPrint" :id="form.id"></PrintTemplate>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, toRefs, reactive, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import http from '@/http.js'
import Big from 'big.js'
import PrintTemplate from '@/print/jingying/SuppliesPrint.vue'
import DepartmentTree from '@/components/bas/DepartmentTree.vue'
import ProjectGridCpt from '@/components/pub/ProjectGridCpt.vue'
import FlowCpt from '@/components/process/FlowCpt.vue'
import FlowOperationCpt from '@/components/process/FlowOperationCpt.vue'
import FlowHistoryCpt from '@/components/process/FlowHistoryCpt.vue'

const props = defineProps({
    id: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['close'])

const processRef = ref(null)

const form = reactive({
    id: '',
    projectCode: '',
    projectName: '',
    departmentId: '',
    departmentCode: '',
    departmentName: '',
    activityDate: '',
    activityAddr: '',
    applyMan: '',
    joinMans: '',
    enterprise: '',
    customAndPost: '',
    planFees: '',
    isWine: 0,
    reasonAndDesired: '',
    isCrmr: 0,
    shippingAddr: '',
    consignee: '',
    consigneePhone: '',
    flowTypeCode: 'SUPPLIES',
    state: '',
    stateName: '',
    handler: '',
    handlerName: '',
    items: [],
    flowList: []
})

const table = reactive({
    data: [],
    selected: [],
    pagination: {
        currentPage: 1,
        pageSizes: [10, 20, 50, 100],
        pageSize: 10,
        total: 0
    }
})

const wineOptions = ref([
    {
        label: '是',
        value: 1
    },
    {
        label: '否',
        value: 0
    }
])

const options = ref([
    {
        label: '有',
        value: 1
    },
    {
        label: '无',
        value: 0
    }
])

const showDepartment = ref(false)
const showProjectGridCpt = ref(false)
const showSaveBtn = ref(false)
const showReviewBtn = ref(false)
const showReviewDialog = ref(false)
const showFlowHis = ref(false)
const showPrint = ref(false)

const closeWindow = () => {
    emit('close')
}

const init = () => {
    if (props.id != '') {
        loadDetail()
    } else {
        showSaveBtn.value = true
        form.departmentId = localStorage.getItem('departmentId')
        form.departmentCode = localStorage.getItem('departmentCode')
        form.departmentName = localStorage.getItem('departmentName')
        form.applyMan = localStorage.getItem('employeeName')
    }
}

const loadDetail = () => {
    http.fetchForm({
        url: '/jingying/supplies/findById',
        method: 'get',
        data: {
            id: props.id
        }
    }).then((res) => {
        let data = res.data
        Object.assign(form, data)

        // 显示保存按钮条件
        let currentUser = localStorage.getItem('username')
        if (data.state == 0 && data.createBy === currentUser) {
            showSaveBtn.value = true
        } else {
            showSaveBtn.value = false
        }
        // 显示审批按钮条件
        if (data.state !== 0 && data.handler === currentUser) {
            showReviewBtn.value = true
        } else {
            showReviewBtn.value = false
        }
        // 显示流程历史
        showFlowHis.value = true
    })
}

const onSubmit = () => {
    let params = JSON.parse(JSON.stringify(form))
    let processData = processRef.value.processList
    let allowSub = true
    for (let i = 0; i < processData.length; i++) {
        if (processData[i].handler == '') {
            allowSub = false
            break
        }
    }
    if (!allowSub) {
        ElNotification({
            title: '提示',
            message: '请选择审核人员',
            type: 'info'
        })
        return
    }
    params['flowList'] = processData
    let items = params.items
    let planFees = 0
    for (let i = 0; i < items.length; i++) {
        let price = new Big(items[i].price)
        let subtotal = price.times(items[i].num)
        params.items[i]['subtotal'] = subtotal
        planFees = subtotal.plus(planFees)
    }
    params['planFees'] = planFees
    console.log(params)
    http.fetchJson({
        url: '/jingying/supplies/save',
        data: params
    }).then((res) => {
        ElNotification({
            title: '提示',
            message: '保存成功',
            type: 'success'
        })
        closeWindow()
    })
}

const addSupplies = () => {
    let newData = {
        id: '',
        name: '',
        model: '',
        unit: '',
        num: '',
        price: '',
        subtotal: '',
        remark: ''
    }
    form.items.push(newData)
}

const deleteRow = (index, rows) => {
    rows.splice(index, 1)
}

const onReview = () => {
    showReviewDialog.value = true
}

const closeReviewDialog = (refresh) => {
    showReviewDialog.value = false
    if (refresh) {
        loadDetail()
    }
}

const chooseDepart = () => {
    showDepartment.value = true
}

const treeSelected = (res) => {
    form.departmentId = res.id
    form.departmentCode = res.code
    form.departmentName = res.label
    showDepartment.value = false
}

const chooseProject = () => {
    showProjectGridCpt.value = true
}

const projectSelected = (res) => {
    let info = res[0]
    form.projectCode = info.code
    form.projectName = info.name
    showProjectGridCpt.value = false
}

const onPrint = () => {
    showPrint.value = true
}

onMounted(() => {
    init()
})
</script>
<style scoped>
@import '@/assets/css/table-form.css';
</style>
